package com.syncomponents.context.support;

import javax.annotation.Resource;

import org.perf4j.aop.Profiled;
import org.springframework.util.Assert;

import com.sunkey.log.audit.annotation.Audit;
import com.sunkey.log.util.JsonUtil;
import com.syncomponents.context.ActionEntity;
import com.syncomponents.context.ComponentFactory;
import com.syncomponents.context.annotation.SynHandler;
import com.syncomponents.message.BaseMessage;
import com.syncomponents.util.ReflectionUtils;

@SynHandler(value = "jsonMessageHandler", type = HandlerType.JSON)
public class JSONMessageHandler implements MessageHandler {

    @Resource
    private ComponentFactory componentFactory;

    @SuppressWarnings("rawtypes")
    @Override   
    @Audit(action = "handle")
    @Profiled(logger = "com.syncomponents.message.JSONMessageHandler")
    public Object handle(String arg0) {
        // TODO 由参数传入
        BaseMessage baseMessage = JsonUtil.fromJson(arg0, BaseMessage.class);

        Assert.notNull(baseMessage.getMsgType(), "msgType is required");
        Assert.notNull(baseMessage.getAction(), "action is required");

        String pathName = baseMessage.getMsgType() + "." + baseMessage.getAction();
        ActionEntity actionEntity = componentFactory.getBean(pathName);

        Object message = JsonUtil.fromJson(arg0, actionEntity.getParamTypes()[0]);

        Object obj = ReflectionUtils.invokeMethod(actionEntity.getMethod(), actionEntity.getInstance(), message);

        return JsonUtil.toJson(obj);
    }

}
